import './Item.css';
import PubSub from 'pubsub-js';
import React, { useState } from 'react';

export default function Item(props) {
  const { todo } = props;
  const [edit, setEdit] = useState(false);
  const [val, setVal] = useState(todo.todoName);
  function changeCheckedHandel() {
    PubSub.publish('changeChecked', todo.id);
  }
  function delTodoHandel() {
    PubSub.publish('delTodo', todo.id);
  }
  function isEditHandel() {
    //按钮取反函数
    setEdit((edit) => {
      let newEdit = !edit;
      console.log(newEdit);
      return newEdit;
    });
  }
  function updateInputHandel(e) {
    setVal((val) => {
      let value = e.target.value;
      return value;
    });
  }
  function updateTodoHandel(e) {
    const todoName = val.trim();
    const data = { todoName, id: todo.id };
    if (todoName === '') return;
    if (e.key !== 'Enter') return;
    PubSub.publish('updateTodo', data);
    isEditHandel();
  }
  return (
    <li>
      <label>
        {edit ? (
          <input type="tetx" value={val} onChange={updateInputHandel} onKeyDown={updateTodoHandel} />
        ) : (
          <>
            <input type="checkbox" checked={todo.isDone} onChange={changeCheckedHandel} />
            <span className={todo.isDone ? '' : 'active'}>{todo.todoName}</span>
          </>
        )}
      </label>
      <button className="btn btn-danger" onClick={delTodoHandel}>
        删除
      </button>
      <button className="btn btn-danger Editor" onClick={isEditHandel}>
        {edit ? '取消' : '编辑'}
      </button>
    </li>
  );
}
